package com.derbysoft.dswitch.adapter.ihg.common.repository.impl;

import com.derbysoft.dswitch.adapter.ihg.common.domain.Direction;
import com.derbysoft.dswitch.adapter.ihg.common.domain.TransactionDetail;
import com.derbysoft.dswitch.adapter.ihg.common.repository.TransactionLogDetailService;
import com.derbysoft.dswitch.adapter.ihg.common.repository.TransactionLogRepository;
import com.derbysoft.dswitch.adapter.ihg.common.utils.DateTimeUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by: jason
 * Date: 2012-06-04
 */
@Service("transactionLogDetailService")
public class TransactionLogDetailServiceImpl
        extends CommonService<TransactionDetail> implements TransactionLogDetailService {
    private static final String DATE_FORMATTER = "yyyyMMdd";
    private static final String DETAIL = "detail";
    private static final String DIRECTION = "direction";

    @Override
    @SuppressWarnings("unchecked")
    public List<TransactionDetail> loadAll(String id, Date date) {
        String sysdate = DateTimeUtils.formatDate(date, DATE_FORMATTER);
        String table = TransactionLogRepository.TRANSACTION_DETAIL_TABLE + TransactionLogRepository.UNDER_LINE + sysdate;
        String field = TransactionLogRepository.TRANSACTION_TABLE + TransactionLogRepository.UNDER_LINE + sysdate;
        String sql = String.format("SELECT detail,direction FROM %s WHERE %s = '%s'", table, field, id);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        List<TransactionDetail> transactionDetails = new ArrayList<TransactionDetail>();
        for (Map<String, Object> map : maps) {
            TransactionDetail transactionDetail = new TransactionDetail();
            transactionDetail.setDetail(map.get(DETAIL).toString());
            transactionDetail.setDirection(Direction.fromRequest(map.get(DIRECTION).toString()));
            transactionDetails.add(transactionDetail);
        }
        return transactionDetails;
    }
}
